//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.chenyue.cm.decrypt;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * @author libingxing
 */
public class EncodeUtils implements Secret<String, String> {

    public static EncodeUtils getInstance() {
        return new EncodeUtils("f2cb9dcb5c0ae0867a566cc8", "de200d9a22495787749b3a36");
    }

    /**
     * IV参数描述
     */
    private IvParameterSpec ivSpec;

    /**
     * 密钥描述
     */
    private SecretKeySpec keySpec;

    /**
     * 加密器
     */
    private Cipher encoder;

    public EncodeUtils(String secretKey, String iv) {
        try {
//            加密器实例化
            encoder = Cipher.getInstance("DESede/CBC/PKCS5Padding");
//            构建密钥描述
            keySpec = new SecretKeySpec(generateKey(secretKey, 24), "DESede");
            ivSpec = new IvParameterSpec(generateKey(iv, 8));
        } catch (Exception var5) {
            var5.printStackTrace();
        }

    }

    @Override
    public String encrypt(String plaintext) throws Exception {
        this.encoder.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
        return new String(Base64.encode(this.encoder.doFinal(plaintext.getBytes()), 0));
    }

    @Override
    public String decrypt(String ciphertext) throws Exception {
        encoder.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
        byte[] b = this.encoder.doFinal(Base64.decode(ciphertext.getBytes(), 0));
        return b != null ? new String(b) : ciphertext;
    }

    private byte[] generateKey(String s, int encodeLength) {
        byte[] a = s.getBytes();
        byte[] b = new byte[encodeLength];

        for (int i = 0; i < a.length && i < b.length; ++i) {
            b[i] = a[i];
        }

        return b;
    }
}
